import axios from "axios";
import { backUrl } from "./setting.js";

axios.defaults.baseURL = backUrl;

export async function checkCookieExistence() {
    let result = {};

    await axios({
        url: '/BuildMind/user/cookie/existence',
        method: 'get',
    }).then((response) => {
        result.status = 1
        result.message = response.message;
    }).catch((error) => {
        console.log(error)
        if (error.response.data) {
            result.status = 0
            result.message = error.response.data.message;
        }
        else if (error.request) {
            result.status = 0
            result.message = "网络错误"
        }
    })
    return result;
}

export async function logout() {
    let result = {};

    await axios({
        url: '/BuildMind/user/cookie/logout',
        method: 'get',
    }).then((response) => {
        result.status = 1
    }).catch((error) => {
        console.log(error)
        if (error.response.data) {
            result.status = 0
            result.message = error.response.data.message;
        }
        else if (error.request) {
            result.status = 0
            result.message = "网络错误"
        }
    })
    return result;
}

export async function getUser() {
    let result = {};
    await axios({
        url: '/BuildMind/user/profile',
        method: 'get',
    }).then((response) => {
        result.status = 1
        result.data = response.data.data

    }).catch((error) => {
        console.log(error)
        if (error.response.data) {
            result.status = 0
            result.message = error.response.data.message;
        }
        else if (error.request) {
            result.status = 0
            result.message = "网络错误"
        }
    })

    return result;
}

export async function setUserName(name) {
    let result = {};
    await axios({
        url: '/BuildMind/user/profile/name',
        method: 'post',
        data: {
            name: name
        },
    }).then((response) => {
        result.status = 1
        result.message = response.data.message;
    }).catch((error) => {
        console.log(error)
        if (error.response.data) {
            result.status = 0
            result.message = error.response.data.message;
        }
        else if (error.request) {
            result.status = 0
            result.message = "网络错误"
        }
    })

    return result;
}

let isUserChanged = false

export function userChanged() {
    return isUserChanged;
}
export function setUserChanged() {
    isUserChanged = true;
}
export function finishUserChanged() {
    isUserChanged = false;
}
